package com.heima.utils.common;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Tess4jUtils {
    static ITesseract tesseract=new Tesseract();
    static {
        tesseract.setDatapath(".\\heima-leadnews-utils\\src\\main\\resources\\Tess4j");
        tesseract.setLanguage("chi_sim");
    }
//    将BufferedImage转发成字符串
    public static String imgtext(BufferedImage file)
    {
        String rslut="";
        try {
            rslut=tesseract.doOCR(file);
        } catch (TesseractException e) {
            throw new RuntimeException(e);
        }
        return rslut;
    }

//    批量将BufferedImage转发成字符串
    public static List<String> imgstext(List<BufferedImage> fileList)
    {
        List<String> resluts=new ArrayList<>();
        for (BufferedImage image:fileList)
        {
            resluts.add(imgtext(image));
        }
        return resluts;
    }

//    将二进制文件转发成BufferedImage
    public static BufferedImage changetoBuff(byte[] bytes)
    {
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
        try {
            BufferedImage image= ImageIO.read(byteArrayInputStream);
            return image;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

//    批量获取图片文字
    public static List<String> SensitiveWordInImage(List<byte[]> bytearr)
    {
        List<BufferedImage> imageword=new ArrayList<>();
        for (byte[] bytes: bytearr)
        {
            imageword.add(changetoBuff(bytes));
        }
        return imgstext(imageword);
    }


}
